const fs = require('fs')
const utility = require('utility')
const config = require('root/config')
const dayjs = require('dayjs')

const utils = {
  removeFile(path) {
    if (!path) {
      console.log('路径不能为空')

      return
    }

    fs.promises.unlink(path, err => {
      if (err) {
        console.log(err)

        return false
      }

      return true
    })
  },
  writeFilePromise(file, data) {
    return new Promise((resolve, reject) => {
      fs.promises.writeFile(file, data, error => {
        if (error) {
          reject(error)
        }

        resolve('success')
      })
    })
  },
  md5Pwd(pwd) {
    const salt = config.secretKey

    return utility.md5(utility.md5(pwd + salt))
  },
  /**
   * 获取日期
   * @param {string} f 格式
   * @returns 结果
   */
  getDayjs(f = 'YYYYMMDD') {
    return dayjs().format(f)
  },
  // 判断是否是图片文件
  isImage(mimeType) {
    const image = ['gif', 'png', 'jpg', 'jpeg', 'bmp', 'webp']

    return image.filter((item) => item === mimeType).length > 0
  },
  // 处理各种catch
  reqHandler(handler) {
    return async(req, res, next) => {
      try {
        await handler(req, res, next)
      } catch (error) {
        console.log('error', error)

        return res.cc('新增错误', 1, error)
        // next(e)
      }
    }
  },
}

module.exports = utils
